const express = require("express");
const route = express.Router();
// 引入pool数据库连接池
const pool = require("../utils/mysql");

// 引入token
const jwt = require('jsonwebtoken')
const SECRET_KEY = 'JWT_SECRET_KEY'
// 引入表单验证
const Joi = require('joi')

// 处理注册业务
route.post('/user/register', (req, res) => {
  let { u_pwd, u_phone } = req.body

  const schema = Joi.object({
    u_pwd: Joi.string().required(),
    u_phone: Joi.string().required()
  })

  const { error } = schema.validate(req.body)
  if (error) {
    res.send({ code: 401, msg: error.details })
    return
  }


  pool.query('select * from pet_user where u_phone = ?', [u_phone], (err, r) => {
    if (err) {
      res.send({ code: 500, msg: err })
    } else {
      // 如果长度为零,没有数据
      if (r.length == 0) {
        let sql = "insert into pet_user(u_id,u_name,u_pwd,u_phone,u_pet_id,u_email,u_sex,u_img) values(null,'张三',MD5(?),?,null,null,null,'uid_00.png')"
        pool.query(sql, [u_pwd, u_phone], (err, r) => {
          if (err) {
            res.send({ code: 400, msg: err })
            // 在服务器端抛出错误
            throw err
          } else {
            res.send({ code: 200, msg: "注册成功" })
          }
        })
      } else {
        // 如果有长度证明手机号已被注册
        res.send({ code: 400, msg: '手机号已被注册' })
      }
    }
  })
})

// 处理登录业务
route.post("/user/login", (req, res) => {
  let { u_phone, u_pwd } = req.body
  // 表单验证
  let schema = Joi.object({
    userphone: Joi.string().required().pattern(new RegExp('^\\w{3,15}$')), // 必填
    password: Joi.string().required().pattern(new RegExp('^\\w{6,15}$')) // 必填
  })
  let { err, value } = schema.validate(req.body)
  if (err) {
    res.send({ code: 400, msg: err }) // 登陆错误
    return
  }
  // 查询表名
  pool.query("select * from pet_user where u_phone=? and u_pwd=MD5(?)", [u_phone, u_pwd], (err, r) => {
    if (err) {
      res.send({ code: 400, msg: err })
      throw err
    }
    if (r.length == 0) {
      res.send({ code: 1001, msg: "账号或密码输入不正确" })
    } else {
      // 获取登录用户对象
      let user = r[0]
      // 为该用户颁发一个token payload保存用户对象信息
      let payload = { id: user.id }
      // expiresIn 有效时间
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1h' })
      // 返回user对象
      user.password = undefined
      res.send({ code: 200, user, token });
    }
  });
});
module.exports = route;
